/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fourbox.server;

import fourbox.Metafile;
import fourbox.client.Client;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hartono
 */
public class ServerUploader implements Runnable {

    String username;
    String host;
    int port;
    List queue;

    public ServerUploader(String username, String host, int port, List queue) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.queue = queue;
    }

    public static void main(String args[]) throws FileNotFoundException, IOException {

        String username = "tono";
        List queue = Collections.synchronizedList(new ArrayList());
        Metafile b = Metafile.createMetafile("Repository/" + username, new File("Repository/tono/b.txt"));
        queue.add(b);

//        File test= Metafile.createFileFromMetafileServer(username, b) ;
//        System.out.println("b "+b);
//        System.out.println("test "+test.getAbsolutePath() );
//        queue.add(Metafile.createMetafile(new File("D:/tes.txt")));
//        queue.add(Metafile.createMetafile(new File("D:/a.pdf")));
//        queue.add(Metafile.createMetafile(username, new File("D:/Fourbox/a/b/c")));               

        ServerUploader sender = new ServerUploader("tono", "localhost", Client.CLIENT_DOWNLOAD_PORT, queue);
        Thread fileSenderThread = new Thread(sender);
        fileSenderThread.start();
    }
//
//    @Override
//    public void run() {
//        try {
//            Socket ServerSocket = new Socket(host, port);
//            DataInputStream in = new DataInputStream(ServerSocket.getInputStream());
//            ObjectOutputStream out = new ObjectOutputStream(ServerSocket.getOutputStream());
//            boolean wait = false;
//            while (queue.size() > 0) {
//                if (in.available() != 0) {
//                    byte[] msg = new byte[5];
//                    if (in.readInt() == 1) {
//                        if (in.read() == 1) {
//                            System.out.println("ACK");
//                            // if ack 
//                            queue.remove(0);
//                            wait = false;
//                        } else {
//                            System.out.println("NAK");
//                            wait=false;
//                        }
//                    } else {
//                        System.out.println("I dont know");
//                    }
//                } else {
//                    if (!wait) {
//                        Metafile headQueue = (Metafile) queue.get(0);
//                        System.out.println("File 1 " + headQueue);
////                        File headFile = new File(headQueue.directory);
//                        File headFile= Metafile.createFileFromMetafileServer(username, headQueue);                        
//                        if (headFile.exists()) {
//                            if (headFile.isFile()) {
//                                // is file
//                                System.out.println("Is file "+headFile.getAbsolutePath());
//                                FileInputStream fis = new FileInputStream(headFile);
//                                out.writeInt(1);
//                                System.out.println("Write int");
//                                out.writeObject(headQueue);
//                                System.out.println("Write metafile");
//
//                                byte[] b = new byte[10];                                
//                                while (fis.available() > 0) {                                    
//                                    int len = fis.read(b);
////                                    System.out.println("baca file "+len);
//                                    out.write(b, 0, len);
//                                }
//                                System.out.println("Write Isi file");
//                                out.flush();                                
//                                
//                                wait = true;
//                                fis.close();
//                                try {
//                                    System.out.println("Sleep");
//                                    Thread.sleep(1000);
//                                    System.out.println("Wake");
//                                    out.reset();
//                                } catch (InterruptedException ex) {
//                                    Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
//                                }
//                            } else {
//                                // is folder
//                                System.out.println("Is folder");
//                                out.writeInt(1);
//                                out.writeObject(headQueue);
//                                out.flush();
//                                wait = true;
//                                try {
//                                    System.out.println("Sleep");
//                                    Thread.sleep(100);
//                                    System.out.println("Wake");
//                                } catch (InterruptedException ex) {
//                                    Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
//                                }
//                            }
//                        } else {
//                            // not exist
//                            System.out.println("Not exist "+headFile.getAbsolutePath());
//                            out.close();
//                            in.close();
//                            ServerSocket.close();
//                            break;
//                        }
//
//                    } else {
//                        // file not exists
//                    }
//                }
//            }
//
//            out.close();
//            in.close();
//            ServerSocket.close();
//            
//        } catch (UnknownHostException ex) {
//            Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }

    @Override
    public void run() {
        System.out.println("Server Uploader : started..there are " + queue.size() + " file to upload");
        try {
            Socket ServerSocket = new Socket(host, port);
            DataInputStream in = new DataInputStream(ServerSocket.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(ServerSocket.getOutputStream());
            boolean wait = false;
            while (queue.size() > 0) {
                if (in.available() != 0) {
                    try {
                        byte[] msg = new byte[5];
//                    System.out.println("in.available "+in.available());
                        System.out.println("Server Uploader : Receive acknowledgement , size "+in.available());
                        if (in.readInt() == 1) {
                            if (in.read() == 1) {
                                System.out.println("Server Uploader : ACK");
                                // if ack 
                                queue.remove(0);
                                wait = false;
                            } else {
                                System.out.println("Server Uploader : NAK");
                                wait = false;
//                                break;
                            }
                        } else {
                            System.out.println("Server Uploader : unknown acknowledgement");
                        }
                    } catch (Exception e) {
                        System.out.println("Server Uploader : error parsing acknowledgment");
                        e.printStackTrace();
                    }
                } else {
                    if (!wait) {
                        Metafile headQueue = (Metafile) queue.get(0);
                        System.out.println("Server Uploader : Sending Metafile -> " + headQueue);

                        if (headQueue.status == Metafile.OK || headQueue.status == Metafile.NEW || headQueue.status == Metafile.UPDATED) {
                            File headFile = Metafile.createFileFromMetafileServer(username, headQueue);
                            if (headFile.exists()) {
                                System.out.println("Server Uploader : " +headFile+ " is exist");
                                if (headFile.isFile()) {
                                    // is file
                                    System.out.println("Server Uploader : " +headFile+ " is file");
                                    FileInputStream fis = new FileInputStream(headFile);
                                    out.writeInt(1);
                                    out.writeObject(headQueue);

                                    byte[] b = new byte[1];
                                    while (fis.available() > 0) {
                                        int len = fis.read(b);
                                        out.write(b, 0, len);
                                    }
                                    out.flush();
                                    System.out.println("Server Uploader : " +headFile+ " content sent");

                                    wait = true;
                                    fis.close();
                                    try {
                                        System.out.println("Server Uploader : Sleep");
                                        Thread.sleep(1000);
                                        System.out.println("Server Uploader : Wake");
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                } else {
                                    // is folder
                                    System.out.println("Server Uploader : " +headFile+ " is folder");
                                    try {
                                        out.writeInt(1);
                                        out.writeObject(headQueue);
                                        out.flush();
                                        System.out.println("Server Uploader " +headQueue+ " folder issue command sent");
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    wait = true;
                                    try {
                                        System.out.println("Server Uploader : Sleep");
                                        Thread.sleep(100);
                                        System.out.println("Server Uploader : Wake");
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                            } else {
                                // not exist
                                System.out.println("Server Uploader : " + headFile+" not exists");
                                out.close();
                                in.close();
                                ServerSocket.close();
                                break;
                            }
                        } else {
                            // delete
//                            System.out.println("Delete file");
                            out.writeInt(1);
//                            System.out.println("Write int");
                            out.writeObject(headQueue);
//                            System.out.println("Write metafile");
                            out.flush();
                            wait = true;
                            System.out.println("Server Uploader : Delete msg sent "+headQueue);

                            try {
                                System.out.println("Server Uploader : Sleep");
                                Thread.sleep(100);
                                System.out.println("Server Uploader : Wake");
                            } catch (InterruptedException ex) {
                                Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }


                    } else {
                        // file not exists
                    }
                }
            }

            out.close();
            in.close();
            ServerSocket.close();


        } catch (UnknownHostException ex) {
            Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ServerUploader.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Server Uploader : thread closed");
    }
}
